package wifiunion.com.notice.crashprocess;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.telephony.TelephonyManager;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

import wifiunion.com.notice.BaseApplication;
import wifiunion.com.notice.CommonUtils;
import wifiunion.com.notice.activity.HomePageActivity;
import wifiunion.com.notice.entity.Param;
import wifiunion.com.notice.utils.SharedPreferencesUtils;


/**
 * Created by Administrator on 2018/3/1.
 */

public class CrashHandler implements Thread.UncaughtExceptionHandler {

    private static CrashHandler crashHandler;

    private Context context;

    private CrashHandler(Context ctx) {
        Thread.setDefaultUncaughtExceptionHandler(this);
        context = ctx;
    }

    public static CrashHandler init(Context ctx) {

        if (crashHandler == null) {
            synchronized (CrashHandler.class) {
                crashHandler = new CrashHandler(ctx);
            }
        }
        return crashHandler;
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
//        Intent intent = new Intent(context, VideoMainActivity.class);
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        context.startActivity(setIntentParams(intent));
        handlerException(ex);

        Intent intent = new Intent(context, HomePageActivity.class);


        PendingIntent restartIntent = PendingIntent.getActivity(
                context, 0, setIntentParams(intent),
                PendingIntent.FLAG_UPDATE_CURRENT);
        //退出程序
        AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 2000,
                restartIntent); // 2秒钟后重启应用


        ((BaseApplication) context.getApplicationContext()).clearActivity();
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(1);
        System.gc();
    }


    private Intent setIntentParams(Intent intent) {
        Param p = SharedPreferencesUtils.getParamSharedPreferences(context);
        if (p != null) {

            Bundle bundle = new Bundle();
            bundle.putString("authtoken", p.mAuthtoken);
            bundle.putString("uuid", p.uuid);
            bundle.putString("placeInfoName", p.placeInfoName);
            bundle.putString("placeInfoLogo", p.placeInfoLogo);
            bundle.putString("server_ip", p.serverIp);
            bundle.putString("server_port", p.serverPort);
            bundle.putString("communityUuid", p.communityUuid);
            bundle.putString("partitionUuid", p.partitionUuid);
            bundle.putString("phone", p.phone);
            bundle.putInt("controlTime", p.controlTime);
            intent.putExtras(bundle);
        }

        return intent;
    }

    private void handlerException(Throwable ex) {


        StringBuffer sb = new StringBuffer("");
        sb.append("####通知模块错误日志####");
        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        String result = writer.toString();
        sb.append(result);

        saveLog(sb.toString());
    }

    /**
     * 保存日志
     *
     * @param exceptionMessage
     */
    private void saveLog(String exceptionMessage) {
        String exceptionFileDir = Environment.getExternalStorageDirectory() + File.separator + "/intelcamera/log/notice";

        File dir = new File(exceptionFileDir);
        if(!dir.exists())
        {
            dir.mkdirs();
        }

        String exceptionFile = exceptionFileDir + File.separator + CommonUtils.getDateTimeSecondStr(System.currentTimeMillis()) + ".txt";

        File file = new File(exceptionFile);

        if (file.exists()) {
            file.delete();
        }
        FileOutputStream fos = null;
        try {

            exceptionMessage = "\n" + exceptionMessage;
            file.createNewFile();
            fos = new FileOutputStream(file);
            byte[] b = exceptionMessage.getBytes();
            fos.write(b);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
